import { findByMyFriends } from '@/api/requests/base';
import router from '@/router/index'
import { ChatMessage } from '@/service/WsService';
import { Toast } from 'vant';

export type Friend = {
  faceImage: string;
  id: string;
  nickName: string;
  nonsenseCode: string;
  phone: string;
  sex: string;
  userId: string;
};

export type HomeChatListItem = {
  nickName: string;
  faceImage: string;
  unReadNum: number;
  lastMsg: string;
}
export const setUserDataCache = (data: any) => {
  localStorage.setItem('userData', JSON.stringify(data))
}
export const setToken = (data: any) => {
  localStorage.setItem('token', data)
}

export const getUserDataCache = () => {
  const data = localStorage.getItem('userData')

  if (data == null) {
    return null
  }
  return JSON.parse(data)
}
export const getToken = () => {
  return localStorage.getItem('token') || null
}

export const removeUserDataCache = () => {
  localStorage.removeItem('userData')
}

export const getUserId = () => {
  return getUserDataCache().userId
}




export const addChatDataCache = (data: ChatMessage) => {
  const temp = getChatDataCache()
  if (temp == null) {
    return
  }
  const chatDataItem: any[] = temp[data.sendUserId] || []
  chatDataItem.push(data)
  temp[data.sendUserId] = chatDataItem
  setChatDataCache(temp)
}

export const addChatDataCaches = (data: ChatMessage[]) => {
  data.forEach(item => {
    addChatDataCache(item)
  })
}

export const setChatDataCache = (data: any) => {
  localStorage.setItem('chatData', JSON.stringify(data))
}
export const getChatDataCache = (): any => {
  const data = localStorage.getItem('chatData')
  if (data == null) {
    return {}
  }
  return JSON.parse(data)

}
export const getFriendData = () => {
  findByMyFriends().then((res: any) => {
    if (res.code == 200) {
      setFriendsDataCache(res.data);
    } else {
      Toast('获取好友数据失败')
    }
  })
}
export const getFriendDataCaches = (): Friend[] => {
  const friendsData = localStorage.getItem('friendsData')
  if (friendsData == null) {
    return []
  }
  return <Friend[]>JSON.parse(friendsData)
}

export const getFriendDataCache = (nonsenseCode: any): Friend | null => {

  const friendsData = getFriendDataCaches()
  if (friendsData == null) {
    return null
  }

  return <Friend><unknown>friendsData[nonsenseCode]
}
export const setFriendsDataCache = (data: Friend[]) => {
  const resultSet: any = {}
  data.forEach(friend => {
    resultSet[friend.userId] = friend
  })
  localStorage.setItem('friendsData', JSON.stringify(resultSet))

}


export const toLogin = () => {
  router.push('/login')
}